/*
 * Copyright 2011-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sabayframework.channel;

/**
 * Lock provides the exclusive access to a channel.
 * Locks should be obtained for short periods of time, for copy data to/from channel.
 * 
 * @author Alex Antonau
 * */
public interface Lock<T> {

	/**
	 * Number of elements locked by this lock.
	 * @return number of locked elements or -1 if the lock was unlocked. 
	 * */
	int size();
	
	/**
	 * Returns a locked element by index.
	 * @param index 0-based index
	 * @throws IndexOutOfBoundsException if index >= size of the lock
	 * @return queue element 
	 * */
	T get(int index);
	
	/**
	 * Sets a locked element by index.
	 * @param index 0-based index
	 * @param elem element
	 * @throws IndexOutOfBoundsException if index >= size of the lock
	 * */
	void set(int index, T elem);
	
	/**
	 * Returns an array of locked elements. 
	 * */
	Object[] toArray();
	
	/**
	 * Unlocks previously locked elements.
	 * For read locks this operation will discard all locked elements from the channel. 
	 * For write locks this operation will add locked elements to the channel.
	 * */
	void unlock();

	/**
	 * Unlocks previously locked elements.
	 * For read locks this operation will keep locked elements in channel.
	 * For write locks cancel will discard all locked elements.
	 * */
	void cancel();
}
